package com.example.loader;

import com.hazelcast.config.Config;
import com.hazelcast.config.MapConfig;
import com.hazelcast.config.MapStoreConfig;
import com.hazelcast.core.EntryAdapter;
import com.hazelcast.core.EntryEvent;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.map.IMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/*
 * @className: HazelcastMapStoreLoader
 * @author: chentao
 * @date: 2025/2/19 上午8:04
 * @Version: 1.0
 * @description:
 */
@Service
public class HazelcastMapStoreLoader implements HazelcastLoader {

    Logger logger = LoggerFactory.getLogger(getClass());

    public static final String MAP_STORE_KEY = "MapStoreImpl";

    public static final String MAP_STORE_CLASS_KEY = "com.example.mapStore.MapStoreFactoryImpl";

    private IMap map = null;

    //定义MapStore配置
    @Override
    public void loadConfig(Config config) throws Exception {
        MapConfig mapConfig = config.getMapConfig(MAP_STORE_KEY);
        MapStoreConfig mapStoreConfig = new MapStoreConfig();
        mapStoreConfig.setEnabled(true);
        mapStoreConfig.setFactoryClassName(MAP_STORE_CLASS_KEY);
        mapConfig.setMapStoreConfig(mapStoreConfig);
        config.addMapConfig(mapConfig);
    }

    //启动并初始化
    @Override
    public void init(HazelcastInstance hazelcastInstance) throws Exception {
        this.map = hazelcastInstance.getMap(MAP_STORE_KEY);
        this.map.addEntryListener(new EntryAdapter() {
            @Override
            public void entryAdded(EntryEvent event) {
                logger.warn("entryAdded entryAdded entryAdded ..." + event.getValue().toString());
            }

            @Override
            public void entryExpired(EntryEvent event) {
                logger.warn("entryExpired entryExpired entryExpired ..." + event.getOldValue().toString());
            }

            @Override
            public void entryRemoved(EntryEvent event) {
                logger.warn("entryRemoved entryRemoved entryRemoved ..." + event.getOldValue().toString());
            }
        }, true);
    }

    public IMap getMap() {
        return map;
    }
}
